package kr.hyosang.dkbs.kiosk.widget;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;

import javafx.geometry.Bounds;
import javafx.scene.media.Media;
import javafx.scene.media.MediaException;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import kr.hyosang.dkbs.kiosk.Env;

public class Player extends WidgetBase {
	private MediaView mdaMedia = null;
	
	private Media [] mediaList = null;
	private MediaPlayer mPlayer = null;
	
	private int nIdx = 0;
	
	public Player(MediaView view) {
		mdaMedia = view;
		
		String videoPath = Env.getRootPath() + "/video";
		File videoRoot = new File(videoPath);
		
		if(videoRoot.exists()) {
			File[] videoList = videoRoot.listFiles();
			ArrayList<Media> mList = new ArrayList<Media>();
			
			for(int i=0;i<videoList.length;i++) {
				if(videoList[i].isFile()) {
					try {
						String url = videoList[i].toURI().toURL().toString();
						Media m = new Media(url);
						
						mList.add(m);
						
						log("File added : " + url);
					}catch(MalformedURLException e) {
						e.printStackTrace();
					}catch(MediaException e) {
						e.printStackTrace();
					}
				}
			}
			
			mediaList = mList.toArray(new Media [0]);
			
			play();
		}else {
			log("No video found : " + videoPath);
		}
	}
	
	private void play() {
		if(mediaList.length > 0) {
			try {
				log(mediaList[nIdx].getSource());
			
				mPlayer = new MediaPlayer(mediaList[nIdx]);
				mdaMedia.setMediaPlayer(mPlayer);
				
				mPlayer.setOnEndOfMedia(mMoveToNext);
				mPlayer.setOnReady(new Runnable() {
		
					@Override
					public void run() {
						Media media = mPlayer.getMedia();
						Bounds area = mdaMedia.getParent().getLayoutBounds();
						
						double wRatio = area.getWidth() / media.getWidth();
						double hRatio = area.getHeight() / media.getHeight();
						
						double ratio = Math.max(wRatio, hRatio);
						double w = media.getWidth() * ratio;
						double h = media.getHeight() * ratio;
						
						if(w <= area.getWidth() && h <= area.getHeight()) {
							//okay.
						}else {
							ratio = Math.min(wRatio, hRatio);
							w = media.getWidth() * ratio;
							h = media.getHeight() * ratio;
						}
						
						if(area.getHeight() > h) {
							mdaMedia.setLayoutY( (area.getHeight() - h) / 2);
						}
						
						if(area.getWidth() > w) {
							mdaMedia.setLayoutX( (area.getWidth() - w) / 2);
						}
					}
				});
				
				mPlayer.play();
			}catch(MediaException e) {
				e.printStackTrace();
			}catch(NullPointerException e) {
				e.printStackTrace();
			}
		}
	}
	
	private Runnable mMoveToNext = new Runnable() {
		@Override
		public void run() {
			nIdx++;
			nIdx = nIdx % mediaList.length;
			
			play();
		}
		
	};

	@Override
	protected String getTag() {
		return "Player";
	}
}
